package common;


import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Spider-Man
 * Date: 2025-09-20
 * Time: 20:32
 */
public class Utils {

    public static WebDriver driver = createDriver();
    public static WebDriver createDriver() {
        WebDriverManager.chromedriver().setup();//下载对应的浏览器驱动
        if(driver == null) {
            WebDriverManager.chromedriver().setup();//下载驱动对象
            ChromeOptions options = new ChromeOptions();//创建配置对象
            options.setExperimentalOption("w3c", false);
            options.addArguments("--remote-allow-origins=*");
            //允许访问所有链接
            driver = new ChromeDriver(options);
            //隐式等待(等待2s搜索页面元素)
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));//防止页面元素未加载完成
//            driver = new ChromeDriver();
        }
        return driver;
    }
    /**
     * 屏幕截图 , 这个方法是在测试用例当中调用的
     * @param str : 截图的类名
     */
    public static void getScreenShot(String str) throws IOException {
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS"); //毫秒级别, 防止截图间隔很端,对截图进行覆盖

        String dirTime = sim1.format(System.currentTimeMillis());// 目录-- 当前日期
        String fileTime = sim2.format(System.currentTimeMillis());// 图片文件

        String fileName = "./src/test/image/" + dirTime + "/" + str + "-" + fileTime + ".png";

        File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        //将截图放到指定文件
        FileUtils.copyFile(srcFile,new File(fileName));
    }

}
